package cat.joronya.supermanager.europeo.team;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Hashtable;
import java.util.Locale;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import cat.joronya.supermanager.europeo.R;
import cat.joronya.supermanager.europeo.Supermanager;
import cat.joronya.supermanager.europeo.market.MarketListActivity;
import cat.joronya.supermanager.europeo.service.SupermanagerServiceHelper;
import cat.joronya.supermanager.europeo.utils.ImageDownloader;

/**
 * My team detail activity shows some fields and list of
 * players.
 * @author pol
 */
public class MyTeamDetailActivity extends ListActivity 
{
	// pel Log
	protected static final String TAG = "supermanager";
	protected static final String URL_PHOTO_PLAYER = 
		"http://www.acb.com/fotos_cara/jugadores/J%sLACB57.jpg";
	
	protected NumberFormat decform = null;
	protected NumberFormat intform = null;
	private SimpleDateFormat simpleDateFormat= null;
	
	protected int idequ;
	protected int day;
	protected int prevDay;
	protected Cursor cursor = null;
	protected Team team;
	protected Cursor daysCursor = null;
	protected Team prevTeam;
	protected Hashtable<String, Float> totals;
	
	protected int status = Supermanager.CLOSED_STATUS;
	protected int lastDay;
	protected Timestamp duetimestamp = null;
	protected int nextDay;
	
	protected String position = null;
	
	protected final ImageDownloader imageDownloader = new ImageDownloader(this, Supermanager.PLAYERS);
	
	protected AbsListView absListView;
	protected ViewFlipper viewFlipper;
	protected static final int SWIPE_MIN_DISTANCE = 60;
	protected static final int SWIPE_MAX_OFF_PATH = 250;
	protected static final int SWIPE_THRESHOLD_VELOCITY = 200;
	
	// dialeg mostrat
	private int dialogShown = -1;
	
	// possible progress dialogs
	private static final int PROGRESS_REFRESH = 1;
	private static final int PROGRESS_RESET_CHANGES = 2;
	private static final int PROGRESS_SELL = 3;
	private static final int PROGRESS_BUY = 4;
	private static final int PROGRESS_CANCEL = 5;
	
	protected MySimpleOnGestureListener mySimpleOnGestureListener;
	protected GestureDetector myGestureDetector;
	protected boolean showingPlayerInfo = false;
	
	protected Animation slideLeftIn;
	protected Animation slideLeftOut;
	protected Animation slideRightIn;
	protected Animation slideRightOut;
	
	protected String cashString = "";
	
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.my_team);
        
       	decform = NumberFormat.getNumberInstance(new Locale("es","ES"));
       	decform.setMinimumFractionDigits(2);
       	intform = NumberFormat.getNumberInstance(new Locale("es","ES"));
       	intform.setGroupingUsed(true);
       	simpleDateFormat = new SimpleDateFormat("EEEE d/MM, HH:mm'h'");
		
       	// load animations
       	slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
        slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
        slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
        slideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
       	
        // guardem id equip i jornada
        idequ = getIntent().getIntExtra("cat.joronya.supermanager.europeo.myteams.idequ",0);
        //day = getIntent().getIntExtra("cat.joronya.supermanager.europeo.myteams.day",1);
        
        // actualitzem dades d'equip
        refreshTeamData();
        
        // tenim cursor?
		if( cursor != null )
			stopManagingCursor(cursor);

		cursor = getContentResolver().query(Supermanager.MyTeamDetail.CONTENT_URI, 
					Supermanager.MyTeamDetail.PROJECTION, 
					Supermanager.MyTeamDetail.ID_EQU+" =? AND "+
					Supermanager.MyTeamDetail.DAY+" =? ", 
					new String[]{""+idequ,""+day}, 
					Supermanager.MyTeamDetail.NUM_POSITION_SORT_ORDER);
		
		startManagingCursor(cursor);
		
		// create gesture listener and detector
		mySimpleOnGestureListener = new MySimpleOnGestureListener();
		myGestureDetector = new GestureDetector(this, mySimpleOnGestureListener);
        
		// adapter
		MyTeamDetailAdapter adapter = new MyTeamDetailAdapter(this, cursor);
        setListAdapter(adapter);
	}
	
	/**
	 * Refresh team data.
	 */
	private void refreshTeamData()
	{
        // retrieve day and status
        Cursor duetimeCursor = getContentResolver().query(Supermanager.Home.CONTENT_URI, 
        		Supermanager.Home.PROJECTION,
        		null, null, Supermanager.Home.DEFAULT_SORT_ORDER);
        if( duetimeCursor.moveToFirst() )
        {
        	View duetimeRow = findViewById(R.id.duetime_linia);
    		
        	// previous day, the day from which show earnings and average
        	prevDay = duetimeCursor.getInt(1);
        	// supermanager status
        	status = duetimeCursor.getInt(2);
        	// day of actual team. Is next day on table
    		day = duetimeCursor.getInt(5);
    		
    		// if 2 day are the same, we are in a day in progress,
    		// we want previous day values
    		if( prevDay == day )
    			prevDay--;
        	
    		// mark lastDay to check menu possible actions
    		lastDay = day;        	
			
        	if( status == Supermanager.OPEN_STATUS )
        	{
        		long timestamp = duetimeCursor.getInt(4);
        		duetimestamp = new Timestamp(timestamp*1000);
        		
        		duetimeRow.setVisibility(View.VISIBLE);
        		TextView closeView = (TextView) findViewById(R.id.my_team_close_label);
        		closeView.setText(getString(R.string.my_team_close_label, day));
        		
        		if( duetimestamp != null )
        		{
        			TextView duetime = (TextView) findViewById(R.id.my_team_duetime);
        			duetime.setText(simpleDateFormat.format(duetimestamp.getTime()));
        		}
        	}
        	else
        	{
        		Cursor myTeamCursor = getContentResolver().query(
        				Supermanager.MyTeamDetail.CONTENT_URI, 
        				new String[]{Supermanager.MyTeamDetail.DAY}, 
        				null, 
        				null, 
        				Supermanager.MyTeamDetail.DAY_SORT_ORDER);
        		if( myTeamCursor.moveToFirst() )
        		{
        			day = myTeamCursor.getInt(0);
        		}
        		myTeamCursor.close();
        		
        		duetimeRow.setVisibility(View.GONE);
        	}
        }
        duetimeCursor.close();
        
		// retrieve current day team data
        team = getTeam(idequ, day);
        
        // retrieve previous day team data
        prevTeam = getTeam(idequ, prevDay);
        
		// set day of the results of team
		TextView dayView = (TextView) findViewById(R.id.my_team_day);
        dayView.setText(getString(R.string.my_team_day, day));
        
        // set team name
        TextView name = (TextView) findViewById(R.id.my_team_name);
        name.setText(team.getName());
        
        // set changes done
        TextView changesDone = (TextView) findViewById(R.id.my_team_changes);
        TextView changesDoneLabel = (TextView) findViewById(R.id.my_team_changes_label);
        if( team.getChangesDone() == 0 )
        {
        	changesDone.setVisibility(View.GONE);
        	changesDoneLabel.setVisibility(View.GONE);
        }
        else
        {
        	changesDone.setVisibility(View.VISIBLE);
        	changesDoneLabel.setVisibility(View.VISIBLE);
        	changesDone.setText(team.getChangesDone()+"");
        }
        
        // set cash
        cashString = intform.format(team.getCash())+"€";
        TextView cash = (TextView) findViewById(R.id.my_team_cash);
        cash.setText(cashString);
        
        // set totals of team, store in class for sharing purposes
		MyTeamDetailProvider provider = new MyTeamDetailProvider();
		totals = provider.getTotals(getApplicationContext(), idequ, day);
        provider.closeHelper();
		
        // set cost of the team
        TextView cost = (TextView) findViewById(R.id.my_team_cost2);
        Float costValue = 0f;
        if( totals != null && totals.get("COST") != null )
        	costValue = totals.get("COST");
        cost.setText(intform.format(costValue)+"€");
        
        // set cost of the team
        TextView price = (TextView) findViewById(R.id.my_team_price2);
        Float priceValue = 0f;
        if( totals != null && totals.get("PRICE") != null )
        	priceValue = totals.get("PRICE");
        price.setText(intform.format(priceValue)+"€");
        
        // set rating of the team
        TextView totalPunts = (TextView) findViewById(R.id.my_team_rating2);
        Float ratingValue = 0f;
        if( totals != null && totals.get("RATING") != null )
        	ratingValue = totals.get("RATING");
        totalPunts.setText(decform.format(ratingValue));
	}
	
	/**
	 * Handle change of orientation.
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) 
	{
		Log.d(TAG,"MyTeamDetailActivity.onConfigurationChanged called");
		super.onConfigurationChanged(newConfig);
		setContentView(R.layout.my_team);

		// actualitzem dades d'equip
        refreshTeamData();
	}

	/**
     * Metode on creem el/s dialeg de la activity.
     * Nomes en tenim un, passem del id.
     */
    @Override
    public Dialog onCreateDialog(int id)
    {
    	Log.d(TAG, "MyTeamDetailActivity.onCreateDialog("+id+")");
    	
    	ProgressDialog progress = null;
    	switch(id)
    	{
    		case PROGRESS_RESET_CHANGES:
    			progress = ProgressDialog.show(this, "", 
    					getResources().getString(R.string.my_team_progress_reset_changes), true);
    			progress.setCancelable(false);
    			break;
    		case PROGRESS_SELL:
    			progress = ProgressDialog.show(this, "", 
    					getResources().getString(R.string.my_team_progress_sell), true);
    			progress.setCancelable(false);
    			break;
    		case PROGRESS_BUY:
    			progress = ProgressDialog.show(this, "", 
    					getResources().getString(R.string.my_team_progress_buy), true);
    			progress.setCancelable(false);
    			break;
    		case PROGRESS_CANCEL:
    			progress = ProgressDialog.show(this, "", 
    					getResources().getString(R.string.my_team_progress_cancel), true);
    			progress.setCancelable(false);
    			break;
    		default:
    		case PROGRESS_REFRESH:
    			progress = ProgressDialog.show(this, "", 
    					getResources().getString(R.string.my_team_progress_refresh), true);
    			progress.setCancelable(false);
    			break;
    	}
    	return progress;
    }
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.my_team, menu);
		
        return true;
    }
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) 
    {
		for( int i=0;  i<menu.size(); i++) 
		{
			MenuItem menuItem = menu.getItem(i);
			boolean isEnabled = false;
			switch(menuItem.getItemId())
			{
				case R.id.cancel_changes:
					// if current no last day no changes
					if( day != lastDay )
						isEnabled = false;
					// id web status is not open no changes
					else if( status != Supermanager.OPEN_STATUS )
						isEnabled = false;
					// if not changes available
					else if( team.getCancelChanges() == 0 )
						isEnabled = false;
					// otherwise enabled
					else
						isEnabled = true;
					break;
				default:
				case R.id.share_my_team:
				case R.id.refresh:
					isEnabled = true;
					break;
			}
			menuItem.setEnabled(isEnabled);
		}
		return super.onPrepareOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		// Handle item selection
		switch (item.getItemId()) 
		{
			case R.id.refresh:
				// mostrar dialeg modal i refresh equip
				dialogShown = PROGRESS_REFRESH;
				showDialog(PROGRESS_REFRESH);
				SupermanagerServiceHelper.getInstance(this).getMyTeamDetail(handler, ""+idequ);
				return true;
			case R.id.cancel_changes:
				dialogShown = PROGRESS_RESET_CHANGES;
				showDialog(PROGRESS_RESET_CHANGES);
				SupermanagerServiceHelper.getInstance(this).resetChanges(handler, ""+idequ);
				return true;
			case R.id.share_my_team:
				Intent sendIntent = new Intent();
				sendIntent.setAction(Intent.ACTION_SEND);
				sendIntent.putExtra(Intent.EXTRA_TEXT, 
					getString(R.string.my_team_share_text, 
						team.getName(), decform.format(totals.get("RATING")) ));
				sendIntent.setType("text/plain");
				startActivity(Intent.createChooser(sendIntent, getString(R.string.my_team_share_title)));
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}
	
	/**
	 * Respon al +info button deshabilitant la list i mostrant
	 * el boto de info.
	 * @param view
	 */
	public void showPlayerInfo(View view) 
	{
		// disable list events and grey it
		ListView list = getListView();
		list.setEnabled(false);
		showingPlayerInfo = true;
		
		// enable info button over grey list 
	    Button infoButton = (Button)findViewById(R.id.player_info);
	    infoButton.setText(view.getTag().toString());
	    infoButton.setVisibility(View.VISIBLE);
	}
	
	/**
	 * Respon al click de la info 'modal'. Amaga info i habilita
	 * la list.
	 * @param view
	 */
	public void hidePlayerInfo(View view) 
	{
		// disable info button
	    Button infoButton = (Button)findViewById(R.id.player_info);
	    infoButton.setVisibility(View.GONE);
	    
	    // enable list events and grey off
		ListView list = getListView();
		list.setEnabled(true);
		showingPlayerInfo = false;
	}

	/**
	 * Respon al click del boto de sell player.
	 * @param view
	 */
	public void sellPlayer(View view)
	{
		Log.d(TAG,"MyTeamDetailActivity.sellPlayer('"+idequ+"','"+view.getTag().toString()+"')");

		// tornem row a l'estat inicial, treiem fling
		mySimpleOnGestureListener.showPreviousOnFlingedRow();
		
		// crida al service
		SupermanagerServiceHelper.getInstance(this).sellPlayer(handler, ""+idequ, view.getTag().toString());
		dialogShown = PROGRESS_SELL;
		showDialog(PROGRESS_SELL);
	}
	
	/**
	 * Respon al click del boto de buy player.
	 * @param view
	 */
	public void buyPlayer(View view)
	{
		Log.d(TAG,"MyTeamDetailActivity.buyPlayer('"+view.getTag().toString()+"')");

		// tornem row a l'estat inicial, treiem fling
		mySimpleOnGestureListener.showPreviousOnFlingedRow();
		
		// crida al service
		dialogShown = PROGRESS_BUY;
		showDialog(PROGRESS_BUY);
		position = view.getTag().toString();
		SupermanagerServiceHelper.getInstance(this).buyMarketPlayers(handler, ""+idequ, position);
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// have been canceled or crashed child activity?
		if( resultCode == Activity.RESULT_CANCELED )
		{
			Log.d(TAG, "MyTeamDetailActivity onActivityResult: canceled!");
			return;
		}
		
		// get player user wants to buy
		String idJug = data.getStringExtra("cat.joronya.supermanager.europeo.market.buyed_player");
		Log.d(TAG, "MyTeamDetailActivity onActivityResult received player["+idJug+"] from MarketActivity");
		
		// call buy on my team syn with that player
		SupermanagerServiceHelper.getInstance(this).buyMyTeamDetailPlayer(handler, ""+idequ, position,idJug);
		dialogShown = PROGRESS_BUY;
		showDialog(PROGRESS_BUY);
	}
	
	/**
	 * Respon al click del boto de cancel change of player.
	 * @param view
	 */
	public void cancelPlayer(View view)
	{
		Log.d(TAG,"MyTeamDetailActivity.cancelPlayer('"+view.getTag().toString()+"')");

		// tornem row a l'estat inicial, treiem fling
		mySimpleOnGestureListener.showPreviousOnFlingedRow();
		
		// crida al service
		SupermanagerServiceHelper.getInstance(this).cancelChange(handler, ""+idequ, view.getTag().toString());
		dialogShown = PROGRESS_CANCEL;
		showDialog(PROGRESS_CANCEL);
	}
	
	/**
	 * Cerca el idjug apartir del codi, si no el troba retorna el codi.
	 * @param codi
	 * @param day
	 * @return
	 */
	private String loadIdjugByCodi(String codi, String day)
	{
		Cursor cursor = getContentResolver().query(Supermanager.Market.CONTENT_URI, 
			Supermanager.Market.PROJECTION, 
			Supermanager.Market.CODI_PLAYER+" = ? AND "+Supermanager.Market.DAY+" = ? ", 
			new String[]{codi,day},
			Supermanager.Market.DEFAULT_SORT_ORDER);
		
		if( cursor.moveToFirst() )
		{
			// recuperem el ID_PLAYER
			String idjug = cursor.getString(1);
			cursor.close();
			
			return idjug;
		}
		else
		{
			// altrament retornem el codi
			return codi;
		}
		
	}
	
	class MyTeamDetailAdapter extends CursorAdapter 
	{
		public MyTeamDetailAdapter(Context theContext, Cursor theCursor) 
		{
			super(theContext, theCursor);
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) 
		{
			// recuperem el codi
			String codi = cursor.getString(3);
			
			// empty card view
			View emptyRow = view.findViewById(R.id.empty_player);
		
			// mostrem banda color amb position
			TextView positionView = (TextView)view.findViewById(R.id.position);
			//positionView.setVisibility(View.VISIBLE);
			String position = cursor.getString(18);
			// bases
			if( position.startsWith("b") )
			{
				positionView.setText(R.string.my_team_row_position_guard);
			}
			// alers
			else if( position.startsWith("a") )
			{
				positionView.setText(R.string.my_team_row_position_forward);
			}
			// pivots
			else 
			{
				positionView.setText(R.string.my_team_row_position_center);
				
			}			

			// si no tenim codi, fitxa buida
			if( codi == null )
			{
				// fem visible la empty card
				emptyRow.setVisibility(View.VISIBLE);
				
				// amaguem banda color
				//View positionView = view.findViewById(R.id.position);
				//positionView.setVisibility(View.GONE);
				
				// amaguem avatar
				View avatarView = view.findViewById(R.id.avatar);
				avatarView.setVisibility(View.GONE);
				
				// amagar stick
				View stickView = view.findViewById(R.id.stick);
				stickView.setVisibility(View.GONE);
				
				// amagar player
				View playerView = view.findViewById(R.id.player);
				playerView.setVisibility(View.GONE);
				
				// activem/desactivem el boto buy del jugador
				Button buyButton = (Button)view.findViewById(R.id.my_team_row_buy_button);
				// just buy button if last day and changes are open
				if( day == lastDay && status == Supermanager.OPEN_STATUS )
				{
					// active button?
					if( cursor.getInt(21) == 0 )
					{
						buyButton.setVisibility(View.GONE);
					}
					else
					{
						buyButton.setVisibility(View.VISIBLE);
						buyButton.setTag(cursor.getString(18));
					}
				}
				else
				{
					buyButton.setVisibility(View.GONE);
				}
				
				// mirem si podem cancelar canvi per mostrar o no el boto
				Button cancelButtonEmptyCard = (Button)view.findViewById(R.id.my_team_row_cancel_button_empty_card);
				// just cancel button if last day and changes are open
				if( day == lastDay && status == Supermanager.OPEN_STATUS )
				{
					if( cursor.getInt(22) == 0 )
					{
						// ocultem boto de cancel
						cancelButtonEmptyCard.setVisibility(View.GONE);
					}
					else
					{
						// mostrem boto de cancel
						cancelButtonEmptyCard.setVisibility(View.VISIBLE);
					
						// set idjug to the button
						cancelButtonEmptyCard.setTag(cursor.getString(18));
					}
				}
				else
				{
					// ocultem boto de cancel
					cancelButtonEmptyCard.setVisibility(View.GONE);
				}
				
				return;
			}
			
			// altrament amaguem vista empty card
			emptyRow.setVisibility(View.GONE);
			
			// setejem l'avatar, la foto del jugador
			ImageView aView = (ImageView)view.findViewById(R.id.avatar);
			aView.setVisibility(View.VISIBLE);
			//imageDownloader.download(String.format(URL_PHOTO_PLAYER, codi), aView);
			
			String idjug = cursor.getString(3);
			
			// si el idjug no es numeric, potser tenim el codi, cerquem idjus apartir del codi
			// si fitxa lliure, no tenim codi
			try{
				Integer.parseInt(idjug);
			}catch(NumberFormatException nfe)
			{
				idjug = loadIdjugByCodi(idjug, day+"");
			}
			
			String playerFoto = "photo_players_europeo_2013/"+idjug+".jpg";
			Drawable drawable;
			try {
				drawable = Drawable.createFromStream(getAssets().open(playerFoto), null);
				aView.setImageDrawable(drawable);
			} catch (IOException e) {
				//e.printStackTrace();
				aView.setImageDrawable(getResources().getDrawable(R.drawable.noavatar));
			}
			
			// si te status, cal ficar stick corresponent
			ImageView statusView = (ImageView)view.findViewById(R.id.stick);
			if( "lesio.png".equals(cursor.getString(24)) )
			{
				statusView.setVisibility(View.VISIBLE);
				statusView.setImageResource(R.drawable.lesio);
				statusView.bringToFront();
			}
			else if( "baixa.png".equals(cursor.getString(24)) )
			{
				statusView.setVisibility(View.VISIBLE);
				statusView.setImageResource(R.drawable.baixa);        				
				statusView.bringToFront();
			}
			else
			{
				// si te nacionality, cal ficar stick corresponent
				if( "nacional.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.nacional);
					statusView.bringToFront();
				}
				else if( "extra.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.extra);        				
					statusView.bringToFront();
				}
				else if( "bandera_26.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_26);        				
					statusView.bringToFront();
				}
				else if( "bandera_27.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_27);        				
					statusView.bringToFront();
				}
				else if( "bandera_28.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_28);        				
					statusView.bringToFront();
				}
				else if( "bandera_29.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_29);        				
					statusView.bringToFront();
				}
				else if( "bandera_31.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_31);        				
					statusView.bringToFront();
				}
				else if( "bandera_32.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_32);        				
					statusView.bringToFront();
				}
				else if( "bandera_35.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_35);        				
					statusView.bringToFront();
				}
				else if( "bandera_36.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_36);        				
					statusView.bringToFront();
				}
				else if( "bandera_39.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_39);        				
					statusView.bringToFront();
				}
				else if( "bandera_43.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_43);        				
					statusView.bringToFront();
				}
				else if( "bandera_57.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_57);        				
					statusView.bringToFront();
				}
				else if( "bandera_58.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_58);        				
					statusView.bringToFront();
				}
				else if( "bandera_59.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_59);        				
					statusView.bringToFront();
				}
				else if( "bandera_61.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_61);        				
					statusView.bringToFront();
				}
				else if( "bandera_62.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_62);        				
					statusView.bringToFront();
				}
				else if( "bandera_63.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_63);        				
					statusView.bringToFront();
				}
				else if( "bandera_64.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_64);        				
					statusView.bringToFront();
				}
				else if( "bandera_65.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_65);        				
					statusView.bringToFront();
				}
				else if( "bandera_66.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_66);        				
					statusView.bringToFront();
				}
				else if( "bandera_67.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_67);        				
					statusView.bringToFront();
				}
				else if( "bandera_68.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_68);        				
					statusView.bringToFront();
				}
				else if( "bandera_69.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_69);        				
					statusView.bringToFront();
				}
				else if( "bandera_70.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_70);        				
					statusView.bringToFront();
				}
				else if( "bandera_71.png".equals(cursor.getString(25)) )
				{
					statusView.setVisibility(View.VISIBLE);
					statusView.setImageResource(R.drawable.bandera_71);        				
					statusView.bringToFront();
				}
				else
				{
					statusView.setVisibility(View.INVISIBLE);
				}
			}
			
			// mostrem el player
			View playerView = view.findViewById(R.id.player);
			playerView.setVisibility(View.VISIBLE);
			
			// fiquem el nom del jugador
			TextView nameView = (TextView)view.findViewById(R.id.player_name);
			nameView.setText(cursor.getString(26));
			
			// fiquem la victoria o no
			TextView victoryView = (TextView)view.findViewById(R.id.player_victory);
			victoryView.setText(cursor.getInt(7)==1?"(+)":"");
			
			// nom de l'equip
			TextView teamView = (TextView)view.findViewById(R.id.player_team);
			teamView.setText(cursor.getString(27));
			
			// nom de l'equip vs
			TextView vsTeamView = (TextView)view.findViewById(R.id.player_team_vs);
			vsTeamView.setText(cursor.getString(28));
			
			// balance de l'equip
			//TextView balanceView = (TextView)view.findViewById(R.id.player_balance);
			//balanceView.setText("");
			
			// preu del jugador
			TextView priceView = (TextView)view.findViewById(R.id.player_price);
			priceView.setText(intform.format(cursor.getInt(6))+"€");
			
			// puntuacio del jugador
			TextView ratingView = (TextView)view.findViewById(R.id.player_rating);
			ratingView.setText(decform.format(cursor.getFloat(8)));
			
			// jornada de compra del jugador
			TextView buyDayView = (TextView)view.findViewById(R.id.player_buy_day);
			int buyDay = cursor.getInt(5);
			if( buyDay != 0 )
				buyDayView.setText("(jª"+buyDay+")");
			else
				buyDayView.setText("");
			
			// preu de compra del jugador
			TextView buyPriceView = (TextView)view.findViewById(R.id.player_buy_price);
			buyPriceView.setText(intform.format(cursor.getInt(4))+"€");
			
			// mitja del jugador
			TextView averageView = (TextView)view.findViewById(R.id.player_average);
			averageView.setText(decform.format(cursor.getFloat(13)));
			
			// activem/desactivem el boto sell del jugador
			TextView sellView = (TextView)view.findViewById(R.id.player_sell_button);
			Button sellButton = (Button)view.findViewById(R.id.my_team_row_sell_button);
			// just sell button if last day and changes are open
			if( day == lastDay && status == Supermanager.OPEN_STATUS )
			{
				if( cursor.getInt(20) == 0 )
				{
					sellView.setVisibility(View.GONE);
					sellButton.setVisibility(View.GONE);
				}
				else
				{
					sellView.setVisibility(View.VISIBLE);
					sellButton.setVisibility(View.VISIBLE);
					sellButton.setTag(cursor.getString(18));
				}
			}
			else
			{
				sellView.setVisibility(View.GONE);
				sellButton.setVisibility(View.GONE);
			}
			
			// activem/desactivem el boto cancel del jugador
			TextView cancelView = (TextView)view.findViewById(R.id.player_cancel_button);
			Button cancelButton = (Button)view.findViewById(R.id.my_team_row_cancel_button);
			// just cancel button if last day and changes are open
			if( day == lastDay && status == Supermanager.OPEN_STATUS )
			{
				if( cursor.getInt(22) == 0 )
				{
					cancelView.setVisibility(View.GONE);
					cancelButton.setVisibility(View.GONE);
				}
				else
				{
					cancelView.setVisibility(View.VISIBLE);
					cancelButton.setVisibility(View.VISIBLE);
					cancelButton.setTag(cursor.getString(18));
				}
			}
			else
			{
				cancelView.setVisibility(View.GONE);
				cancelButton.setVisibility(View.GONE);
			}
			
			// activem/desactivem la view +info del jugador
			TextView infoView = (TextView)view.findViewById(R.id.player_info_button);
			Button infoButton = (Button)view.findViewById(R.id.my_team_row_info_button);
			if( cursor.getString(29) == null )
			{
				infoView.setVisibility(View.GONE);
				infoButton.setVisibility(View.GONE);
			}
			else
			{
				infoView.setVisibility(View.VISIBLE);
				infoButton.setVisibility(View.VISIBLE);
				infoButton.setTag(cursor.getString(29));
			}
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) 
		{
			// create the new view
			LayoutInflater inflater = LayoutInflater.from(context);
			ViewFlipper row = (ViewFlipper)inflater.inflate(R.layout.my_team_row, parent, false);
			
			// bind data to the row view
			bindView(row, context, cursor);	
			
			// if we have player and actions on it, register fling listener
			row.setOnTouchListener(new View.OnTouchListener() 
	        {
	            public boolean onTouch(View v, MotionEvent event) 
	            {
	            	if( showingPlayerInfo )
	            		return true;
	            	
	            	//Log.d(TAG,"MyTeamDetailAdapter.View.OnTouchListener.onTouch class: "+v.getClass().getName());
	            	
	            	// register row flipper to access it on gesture detector
	            	mySimpleOnGestureListener.setViewFlipper((ViewFlipper)v);
	    			
	            	if (myGestureDetector.onTouchEvent(event)) {
	                    return true;
	                }
	                return false;
	            }
	        });
			
			return row;
		}
	}	
	
	// Gesture listener que detecta el fking i passa a la view previa o posterior
	class MySimpleOnGestureListener extends SimpleOnGestureListener 
	{
		private ViewFlipper viewFlipper = null;
		private boolean flipperChanged = false;
		private boolean flipperLongPressed = false;
		
		/**
		 * Sets the view flipper of the last row flinged, so on any event on list,
		 * return view flipper registered to initial status, so hide buttons.
		 * @param theViewFlipper
		 */
		public void setViewFlipper(ViewFlipper theViewFlipper)
		{
			// si tenim longPress pero al mateix flipper, no fem res
			if( flipperLongPressed && viewFlipper == theViewFlipper )
			{
				//Log.d(TAG, "MySimpleOnGestureListener.setViewFlipper longPress and the same flipper, nothing to do.");
				return;
			}
			
			// si ens canvien el flipper, mostrem 1a vista del flipper
			if( viewFlipper != theViewFlipper )
			{
				//Log.d(TAG, "MySimpleOnGestureListener.setViewFlipper different flipper, show previos view.");
				showPreviousOnFlingedRow();
			}
			
			// registrem el flipper de la fila nova
			viewFlipper = theViewFlipper;
		}
		
		/**
		 * For calling externally and return the row to first status.
		 */
		public void showPreviousOnFlingedRow()
		{
			// si el flipper estava canviat, el tornem a lloc
			if( flipperChanged )
			{
				//Log.d(TAG, "MySimpleOnGestureListener.showPreviousOnFlingedRow changing to previous flipper view");
				viewFlipper.setInAnimation(slideRightIn);
                viewFlipper.setOutAnimation(slideRightOut);
				viewFlipper.showPrevious();
				flipperChanged = false;
			}
		}
		
		/**
		 * Overriden to avoid 'bug' and prevent onFling from not being called as
		 * described in http://code.google.com/p/android/issues/detail?id=8233
		 */
		@Override
		public boolean onDown(MotionEvent e)
		{
			//Log.d(TAG, "MySimpleOnGestureListener.onDown disable possible previous longPress event");
			
			// desmarquem possible previ onLongPress
			flipperLongPressed = false;
			
			return true;
		}
		
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) 
        {
            try 
            {
            	//Log.d(TAG, "MySimpleOnGestureListener.onFling");
            	if( Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH )
                    return false;
                
                // left to right swipe, left fling
                if( e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY ) 
                {
                	// mirem si es fitxa lliure
        			View emptyRow = viewFlipper.findViewById(R.id.empty_player);
        			if( emptyRow.getVisibility() != View.VISIBLE )
        			{
        				flipperChanged = true;
        				viewFlipper.setInAnimation(slideLeftIn);
        				viewFlipper.setOutAnimation(slideLeftOut);
        				viewFlipper.showNext();
        			}
        			else
        			{
        				Log.d(TAG,"MyTeamDetail onFling to empty card, nothing to do.");
        			}
                }  
                else if(e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY )
                {
                	// nothing to do on right fling
                }
            	return true;
            }
            catch(Exception e){
                // nothing
            }
            return false;
        }

		@Override
		public void onLongPress(MotionEvent e) 
		{
			//Log.d(TAG,"MyTeamDetail onLongPress");
			
			// mirem si es fitxa lliure
			View emptyRow = viewFlipper.findViewById(R.id.empty_player);
			if( emptyRow.getVisibility() != View.VISIBLE )
			{
				flipperChanged = true;
				flipperLongPressed = true;
				viewFlipper.setInAnimation(slideLeftIn);
				viewFlipper.setOutAnimation(slideLeftOut);
				viewFlipper.showNext();
			}
		}
    }
	
	
	private Team getTeam(int idequ, int day)
	{
		Cursor c = getContentResolver().query(Supermanager.MyTeam.CONTENT_URI, 
				Supermanager.MyTeam.PROJECTION, 
				Supermanager.MyTeam.ID_EQU + " = ? AND "+
				Supermanager.MyTeam.DAY + " = ? ",
				new String[]{
					""+idequ,
					""+day
				},
				null);
		
		Team team = null;
		
		if( c.moveToFirst() )
		{
			team = new Team();
			team.setIdEqu(c.getString(1));
			team.setName(c.getString(2));
			team.setDay(c.getInt(3));
			int cash = c.getInt(14);
			team.setCash(cash);
			int earnings = c.getInt(15);
			team.setEarnings(earnings);
			int cancelChanges = c.getInt(20);
			team.setCancelChanges(cancelChanges);
			float points = c.getFloat(4);
			team.setPoints(points);
			int changesDone = c.getInt(21);
			team.setChangesDone(changesDone);
			int changesTotal = c.getInt(22);
			team.setChangesTotal(changesTotal);
		}
		
		c.close();
		
		return team;
	}
		
	private Handler handler = new Handler() 
    { 
        @Override 
        public void handleMessage(Message msg)
        { 
            //get data from msg 
        	int status = msg.getData().getInt(Supermanager.STATUS_MESSAGE);
            Log.d(TAG, "MyTeamDetailActivity received status: "+status);
            
            if( dialogShown != -1 )
            {
            	dismissDialog(dialogShown);
            }
            
            // refresh ok
            if( status == Supermanager.MY_TEAM_DETAIL_PARSED_OK )
            {
            	// refresh team data
            	refreshTeamData();
            	
            	Toast.makeText(getApplicationContext(), 
		        	R.string.my_team_toast_refresh_ok, 
            		Toast.LENGTH_SHORT).show();
            }
            // reset changes ok
            else if( status == Supermanager.MY_TEAM_DETAIL_RESET_CHANGES_OK )
            {
            	// refresh team data
            	refreshTeamData();
            	
            	Toast.makeText(getApplicationContext(), 
		        	R.string.my_team_toast_reset_changes_ok, 
            		Toast.LENGTH_SHORT).show();
            }
            // buy player ok
            else if( status == Supermanager.MY_TEAM_DETAIL_BUY_OK )
            {
            	// refresh team data
            	refreshTeamData();
            	
            	Toast.makeText(getApplicationContext(), 
		        	R.string.my_team_toast_buy_ok, 
            		Toast.LENGTH_SHORT).show();
            }
            // sell player ok
            else if( status == Supermanager.MY_TEAM_DETAIL_SELL_OK )
            {
            	// refresh team data
            	refreshTeamData();
            	
            	Toast.makeText(getApplicationContext(), 
		        	R.string.my_team_toast_sell_ok, 
            		Toast.LENGTH_SHORT).show();
            }
            // cancel change of player ok
            else if( status == Supermanager.MY_TEAM_DETAIL_CANCEL_OK )
            {
            	// refresh team data
            	refreshTeamData();
            	
            	Toast.makeText(getApplicationContext(), 
		        	R.string.my_team_toast_cancel_ok, 
            		Toast.LENGTH_SHORT).show();
            }
            // get market buy players status (red, orange, black) ok.
            else if( status == Supermanager.MARKET_BUY_OK )
            {
            	// jump to other activity to pick player
            	Log.d(TAG, "Show MarketBuy");
            	Intent intent = new Intent(Intent.ACTION_PICK, 
            			Supermanager.Market.CONTENT_URI, getApplicationContext(), MarketListActivity.class);
            	intent.putExtra("cat.joronya.supermanager.europeo.myteamdetail.position", position);
            	intent.putExtra("cat.joronya.supermanager.europeo.myteamdetail.cash", cashString);
            	startActivityForResult(intent, 1);
            }
            // altrament error
            else
            {
            	// reset changes error
            	if( dialogShown == PROGRESS_RESET_CHANGES )
            		Toast.makeText(getApplicationContext(), 
            				R.string.my_team_toast_reset_changes_fail, 
            				Toast.LENGTH_SHORT).show();
            	// buy player error
            	else if( dialogShown == PROGRESS_BUY )
            		Toast.makeText(getApplicationContext(), 
            				R.string.my_team_toast_buy_fail, 
            				Toast.LENGTH_SHORT).show();
            	// sell player error
            	else if( dialogShown == PROGRESS_SELL )
            		Toast.makeText(getApplicationContext(), 
            				R.string.my_team_toast_sell_fail, 
            				Toast.LENGTH_SHORT).show();
            	// cancel change of player error
            	else if( dialogShown == PROGRESS_CANCEL )
            		Toast.makeText(getApplicationContext(), 
            				R.string.my_team_toast_cancel_fail, 
            				Toast.LENGTH_SHORT).show();
            	// refresh or other error
            	else 
            		Toast.makeText(getApplicationContext(), 
            				R.string.my_team_toast_refresh_fail, 
            				Toast.LENGTH_SHORT).show();
            }
            
        	dialogShown = -1;
            super.handleMessage(msg); 
        } 
    };
}
